import { createRouter, createWebHistory } from 'vue-router'
import { authUserInfo, getUserInfo } from '@/api/wechat/auth'
import { Wechat_info } from '@/constant/wechat_info'
import { showFailToast, showSuccessToast } from 'vant'
//@ts-ignore
import { cookieUtil } from '@/utils/cookie.js'
import { getUserWechatAccounts, getWechatAccounts } from '@/api/wechat/app'
import { addWechatUser } from '@/api/wechat/user'
import type { UserWechatAccounts } from '@/api/types'
import { routes } from '@/router/routes'

const router = createRouter({
  // @ts-ignore
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

let user_wechat_account: UserWechatAccounts = {
  userName: cookieUtil.get('user_name'),
  tel: cookieUtil.get('user_tel'),
  accountId: null,
  openid: cookieUtil.get('open_id'),
  nickname: cookieUtil.get('user_nickname'),
}

function addWechatUserLink(accountId: number) {
  user_wechat_account.accountId = accountId
  // 先获取一下用户有没有关联
  getUserWechatAccounts(user_wechat_account.openid).then((res) => {
    if (res.data.accountId == null) {
      // 需要去绑定微信
      addWechatUser(user_wechat_account).then((res: any) => {
        if (res.code == 200) {
          showSuccessToast('绑定微信成功,正在为您跳转页面...')
          router.push('/')
        }
      })
    } else {
      showSuccessToast('您已经绑定过微信,正在为您跳转页面...')
      router.push('/')
    }
  })
}

// 路由守卫 主要是监听 对于每一次请求都会执行
router.beforeEach(async (to, from, next) => {
  const href = new URL(window.location.href)
  const app_code = href.searchParams.get('code')
  const token = cookieUtil.get('user_token')
  // 只拦截授权链接
  if (app_code && to.name !== '/login/once') {
    if (!token) {
      console.log('用户无token，开始授权')
      const query = {
        code: app_code,
        state: 'login',
        appid: Wechat_info.appId,
      }
      try {
        const res: any = await authUserInfo(query)
        if (res.code === 200) {
          showSuccessToast({ message: '微信授权成功~' })
          addStorage(res)
        } else {
          showFailToast('微信授权失败!')
          clearStorage()
        }
      } catch (error) {
        showFailToast('请重新授权登录!' + error)
        clearStorage()
      } finally {
        next()
      }
    } else {
      console.log('用户有token，放行')
      return next()
    }
  } else {
    return next()
  }

  if (token) {
    getUserInfo(cookieUtil.get('open_id'))
      .then((res: any) => {
        if (res.code == 200) {
          if (res.data.tel == null || res.data.userName == null) {
            router.push('/login/before')
          } else {
            getWechatAccounts(Wechat_info.appId).then((res: any) => {
              if (res.code == 200) {
                if (res.data == null) {
                  showFailToast('未找到相关公众号信息!')
                } else {
                  addWechatUserLink(res.data)
                }
              }
            })
          }
        }
      })
      .catch((err) => {
        showFailToast('错误:' + err)
      })
  }
})

// 存储信息
export function addStorage(res: any) {
  console.log(res)
  sessionStorage.setItem('open_id', res.userInfo.openid)
  cookieUtil.set('user_token', res.token)
  cookieUtil.set('open_id', res.userInfo.openid)
  cookieUtil.set('user_nickname', res.userInfo.nickname)
  cookieUtil.set('user_avator', res.userInfo.headImgUrl)
}

// 删除信息
export function clearStorage() {
  sessionStorage.removeItem('open_id')
  cookieUtil.remove('user_token')
  cookieUtil.remove('open_id')
  cookieUtil.remove('user_nickname')
  cookieUtil.remove('user_avator')
}

export default router
